/// https://developer.chrome.com/docs/extensions/get-started/tutorial/scripts-activetab?hl=zh-cn

let selectList = [];
let isSingle = false;
let sketchJson;
let originData = [];
let customCache = {};
let virtualMap = {};
let virtualChildren = [];

let hideRelatedVirtual = false;

let disable = false;

let curCache;

function inspect() {
    console.log("inspect")

    setTimeout(function () {
        let panel = $('.info-drawer');
        panel.after(getPanel())
        panel.after(helpDialog());
        panel.after(getSettingsPanel());

        $("#clear_select").click(clearSelected);
        $("#generate_group").click(generateGroup);
        $("#choose_parent").click(chooseParent);
        $("#plug_in_copy_code").click(copyCode);
        $("#plug_in_copy_string").click(copyString);
        $("#plug_in_delete_select").click(deleteSelectedVirtual);
        $("#plug_in_hide_related").click(switchRelatedVirtual);
        $("#plug_in_auto_layout").click(clickAutoLayout);
        $("#plug_in_find_parent").click(autoFindParent);
        $("#plug_in_find_child").click(autoFindChild);
        $("#plug_in_help").click(showHelp);
        $("#help_ok").click(closeHelp);
        $("#plug_in_setting").click(showSetting);
        $("#plug_in_close_setting").click(closeSetting);

        // 输入框输入事件代理回调
        $("input[id='info_view_define_name']").on('change', function () {
            var text = info_view_define_name.value + "";
            if (curCache) {
                curCache.name = text;
                if (curCache.isVirtual) {
                    refreshVirtualList();
                }
                showCode(curCache);
            }
            showToast("命名成功");
        });

        // 组件类型选择事件代理回调
        $("select[id='info_view_type']").on('change', function () {
            var text = info_view_type.value + "";
            if (curCache) {
                curCache.subType = text;
                if (isGroup(curCache)) {
                    curCache.type = text;
                }
                if (curCache.isVirtual) {
                    refreshVirtualList();
                }
                showCode(curCache);
            }
        });

        $("input[id='multilple_select']").on("change", function () {
            isSingle = !$(this).prop("checked");
            console.log("isSingle:", isSingle);
        });

        initSetting();

        console.log("inspect end")
    }, 500);
}

/// 监听元素点击事件
function intercept() {
    console.log("intercept")

    $("[data-index]").on("click", function () {
        if (disable) return;

        let index = $(this).attr("data-index");
        let id = $(this).attr("data-id");

        if (isSingle) {
            clearSelected();
        }

        var data = null;
        if (index <= originData.length) {
            data = originData[index];
        }
        if (!data) {
            console.log("no data", index, id)
            return;
        }
        console.log("intercept click", index, id, data)

        if (selectList.includes(index)) {
            selectList.splice(selectList.indexOf(index), 1);
            $(this).css({ "outline": "" });
        } else {
            selectList.push(index)
            $(this).css({ "outline": "#4DE17D solid 1px" });
        }

        curCache = getCache(data);
        showElementInfo(curCache);
        showRelated(curCache);

        showCode(curCache);
    });

    console.log("intercept end")
}

function getCache(data) {
    customCache[data.id] = customCache[data.id] || {
        id: data.id,
        data: data
    };
    if (!customCache[data.id].index) {
        for (let i = 0; i < originData.length; i++) {
            if (originData[i].id == data.id) {
                customCache[data.id].index = i;
                break;
            }
        }
    }
    return customCache[data.id];
}

function showElementInfo(cache) {
    let data = cache.data;
    if (!data) return
    
    console.log("showElementInfo: ", data.type);
    $("select[id='info_view_type']").children().remove();

    if (virtualMap[data.id]) {
        $("select[id='info_view_type']").append(getTypeOption(virtualMap[data.id].type));
    } else {
        $("select[id='info_view_type']").append(getTypeOption(cache.type || figure(data), cache.subType));
    }

    $("span[id='info_view_position']").text(position(data));

    $("input[id='info_view_define_name']").val(cache.name != null ? cache.name : '');
    showParentInfo(cache.parent || {});
}

function showParentInfo(cache) {
    let data = cache.data;
    if (cache.type) {
        $("span[id='info_view_layer_union']").text(cache.type);
    } else if (data) {
        $("span[id='info_view_layer_union']").text(figure(data));
    } else {
        $("span[id='info_view_layer_union']").text("");
    }
}

function clearSelected() {
    for (let i = 0; i < selectList.length; i++) {
        $("[data-index=" + selectList[i] + "]").css({ "outline": "" });
    }
    for (let i = 0; i < virtualChildren.length; i++) {
        $("[data-index=" + virtualChildren[i] + "]").css({ "outline": "" });
    }
    curCache = null;
    selectList.length = 0;
    virtualChildren.length = 0;
    refreshVirtualList();
}

function chooseParent() {
    if (selectList.length == 0) return;

    let last = selectList.slice(-1);
    let data = originData[last[0]];
    let cache = getCache(data);
    if (cache && cache.parent) {
        curCache = cache.parent;
        clearSelected();
        selectList.push(cache.parent.index);
        $("[data-index=" + cache.parent.index + "]").css({ "outline": "#4DE17D solid 1px" });
        showElementInfo(cache.parent);
        showCode(curCache);
    }
}

function generateGroup() {
    let virtualDatas = getSelectVirtualList();

    if (selectList.length == 0 && virtualDatas.length == 0) {
        return;
    }

    let selectDatas = selectList.map(function (item) {
        let data = originData[item];
        return data;
    });

    selectDatas.push(...virtualDatas);

    if (selectDatas.length == 1) {
        console.log("single")
        return;
    }

    let biggest = findBiggest(selectDatas);
    let biggestType = figure(biggest);
    let notParent = true;
    if (biggestType == "Container") {
        if (selectDatas.length > 2) {
            notParent = true;
        } else {
            notParent = selectDatas.some(function (item) {
                if (item.id != biggest.id && !isParent(biggest, item)) {
                    return true;
                }
                return false;
            })
        }
    } else if (biggestType == "SizedBox") {
        notParent = selectDatas.some(function (item) {
            if (item.id != biggest.id && !isParent(biggest, item)) {
                return true;
            }
            return false;
        })
    }

    if (notParent) {
        console.log("no Parent")
        virtualGroup(selectDatas);
        if (curCache && curCache.parent) {
            showParentInfo(curCache.parent);
        }
    } else {
        console.log("biggest parent")
        selectDatas.forEach(function (item) {
            if (item.id != biggest.id) {
                setupLevel(biggest, item);
            }
        })
        let childrens = selectDatas.filter(function (item) {
            return item.id != biggest.id;
        })

        let layout = supposeLayout(childrens);
        console.log("biggest layout: ", layout);
    }
    clearEmptyVirtual();
    clearSelected();
}

function setupLevel(parentData, childData) {
    let child = getCache(childData)

    let parent = getCache(parentData)

    parent.children = parent.children || [];
    let exist = parent.children.some(function (item) {
        return item.data.id == child.data.id
    })
    if (exist) {
        return;
    }
    parent.children.push(child);
    removeFromParent(child);
    child.parent = parent;

    if (selectList.length == 0) return;
    let last = selectList.slice(-1);
    if (originData[last[0]].id == childData.id) {
        showParentInfo(parent);
    }

    if (parent.isVirtual) {
        let maxIndex = 0;
        parent.children.forEach(function (item) {
            maxIndex = Math.max(maxIndex, item.index);
        });
        parent.index = maxIndex;
    }

    let selectDatas = parent.children.map(function (item) {
        return item.data;
    });
    parent.type = supposeLayout(selectDatas);
}

function removeFromParent(cache) {
    if (cache.parent && cache.parent.children) {
        cache.parent.children = cache.parent.children.filter(function (item) {
            return item.data.id != cache.data.id
        })
    }
    cache.parent = null;
}

function clearEmptyVirtual() {
    for (let id in virtualMap) {
        let item = virtualMap[id];
        if (item.children && item.children.length == 0) {
            delete virtualMap[id];
        }
    }
    refreshVirtualList();
}

function virtualGroup(selectDatas) {
    let virtual = {
        isVirtual: true,
        data: {},
        id: guid()
    }

    virtual.data.id = virtual.id;

    customCache[virtual.id] = virtual;

    selectDatas.forEach(function (item) {
        setupLevel(virtual, item);
    });

    let layout = supposeLayout(selectDatas);
    virtual.type = layout;
    fixLayoutSize(virtual);

    console.log("virtual layout: ", layout);

    virtualMap[virtual.id] = virtual;
}

function refreshVirtualList() {
    $("#info_view_virtual_list").children().remove();
    let list = [];

    for (let id in virtualMap) {
        let item = virtualMap[id];
        if (hideRelatedVirtual && item.parent) {
            continue;
        }

        let type = item.type;
        if (item.name) {
            type = type + " - " + item.name;
        }
        if (!item.parent) {
            type = type + " - 未关联";
        }

        let content = getVirtualItem();
        content = content.replace(/{virtual-id}/g, item.id);
        content = content.replace(/{text}/g, type);
        list.push(content);
    }

    $("#info_view_virtual_list").append(list.join(""));
    listenVirtualList();
}

function listenVirtualList() {
    $("span[class*='virtual_title']").click(function () {
        let id = $(this).attr("virtual-id");
        let cache = virtualMap[id];
        console.log(cache);

        if (!cache) return;

        curCache = cache;

        showRelated(cache);

        showElementInfo(cache);

        showCode(cache);
    })
}

function getSelectVirtualList(useCache) {
    let list = [];
    $("input[virtual-id]").each(function () {
        let selected = $(this).is(":checked")
        if (selected) {
            let id = $(this).attr("virtual-id");
            let cache = customCache[id];
            if (cache) {
                if (useCache) {
                    list.push(cache);
                } else if (cache.data) {
                    list.push(cache.data);
                }
            }
        }
    })
    return list;
}

function copyCode() {
    let text = $("#info_view_code").text();
    copyToClipboard(text);
    showToast("复制成功");
}

function copyString() {
    let text = stringList.join(",\n\t");
    if (text.length > 0) {
        copyToClipboard(text);
        showToast("复制成功");
    } else {
        showToast("无可复制内容");
    }
}

function deleteSelectedVirtual() {
    let list = getSelectVirtualList(true);
    list.forEach(function (item) {
        let id = item.id;
        if (item.parent) {
            removeFromParent(item);
        }

        if (item.children) {
            item.children.forEach(function (child) {
                removeFromParent(child);
            });
            item.children.length = 0;
        }

        delete virtualMap[id];
        delete customCache[id];
    })
    refreshVirtualList();
}

function switchRelatedVirtual() {
    hideRelatedVirtual = !hideRelatedVirtual;
    if (hideRelatedVirtual) {
        $("#plug_in_hide_related").text("显示已关联");
    } else {
        $("#plug_in_hide_related").text("隐藏已关联");
    }
    refreshVirtualList();
}

function clickAutoLayout() {
    let group;
    if (isAndroid) {
        group = constrainLayout(curCache, originData);
    } else {
        group = spreadLayout(curCache, originData);
    }
    showCode(group);
    refreshVirtualList();
}

function showCode(cache) {
    let code = resetAndExport(cache);
    code = code.replace(/\)\s*,\s*\n\s*\)/g, "))");
    code = code.replace(/\)\s*,\s*\n\s*\]/g, ")]");
    code = code.replace(/\]\s*,\s*\n\s*\]/g, "]]");
    code = code.replace(/\]\s*,\s*\n\s*\)/g, "])");

    code = code.replace(/pt\s*,\s*\n\s*\]/g, "pt]");
    code = code.replace(/pt\s*,\s*\n\s*\)/g, "pt)");

    code = code.replace(/return\s+\n\s+/g, "return ");

    // code = formatFlutterDart(code, "flutter");
    code = formatDart(code);
    $("#info_view_code").text(code);
}

function autoFindParent() {
    let selectDatas = selectList.map(function (item) {
        let data = originData[item];
        return data;
    });
    for (let i = 0; i < selectDatas.length; i++) {
        let cache = getCache(selectDatas[i]);

        let parent = findParent(cache, originData);

        if (parent) {
            console.log("parent", parent);

            setupLevel(parent, cache.data);

            let parentCache = getCache(parent);
            showRelatedParent(parentCache.index);
        }
    }
}

function autoFindChild() {
    let selectDatas = selectList.map(function (item) {
        let data = originData[item];
        return data;
    });
    for (let i = 0; i < selectDatas.length; i++) {
        let cache = getCache(selectDatas[i]);

        let children = findChild(cache, originData);
        console.log("children", children)

        let parentData = cache.data;
        if (figure(cache.data) == "Container" && children.length > 1) {
            let virtual = newVirtual();
            setupLevel(cache.data, virtual.data);
            parentData = virtual.data;
            parentData.x = cache.data.x;
            parentData.y = cache.data.y;
            parentData.width = cache.data.width;
            parentData.height = cache.data.height;
        }

        for (let i = 0; i < children.length; i++) {
            let child = children[i];
            setupLevel(parentData, child);
            let childCache = getCache(child);
            showRelatedChild(childCache.index);
        }
    }
}

function showRelated(cache) {
    if (cache.parent) {
        if (!cache.parent.isVirtual) {
            showRelatedParent(cache.parent.index);
        }
    }

    if (cache.children) {
        for (let i = 0; i < cache.children.length; i++) {
            if (!cache.children[i].isVirtual) {
                showRelatedChild(cache.children[i].index);
            }
        }
    }
}

function showRelatedChild(index) {
    $("[data-index=" + index + "]").css({ "outline": "blue solid 1px" });
    virtualChildren.push(index);
}

function showRelatedParent(index) {
    $("[data-index=" + index + "]").css({ "outline": "red solid 1px" });
    virtualChildren.push(index);
}